<template>
  <el-dialog
    v-model="previewVisible"
    title="表单预览"
    width="1120px"
    top="3vh"
    class="preview-dialog"
    modal-class="preview-dialog-modal"
    lock-scroll
    @close="handleClose"
  >
    <div class="form-preview">
      <!-- 表单预览容器 -->
      <el-form class="preview-canvas" :model="previewData" ref="formRef">
        <div
          v-for="item in previewComponents"
          :key="item.id"
          class="preview-component"
          v-show="!isComponentHidden(item.id)"
          :style="getComponentStyle(item)"
        >
          <FormComponent
            :component="{
              ...item,
              value: previewData[item.props?.field],
            }"
            :mutex-state="mutexState"
            :relate-state="relateState"
            :is-preview="true"
          />
        </div>
      </el-form>
    </div>
    <template #footer>
      <el-button @click="handleClose">关闭</el-button>
      <el-button @click="handleSubmit(formRef)" type="primary"
        >提交表单</el-button
      >
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, computed, onMounted, onUnmounted, nextTick } from "vue";
import { ElMessage } from "element-plus";
import type { FormInstance } from "element-plus";
import FormComponent from "./FormComponent.vue";
import type {
  CanvasComponent,
  MutexRule,
  RelateConfig,
} from "@/views/lowCode/types";
import { EventBus } from "@/utils/eventBus";
import _ from "lodash";

const props = defineProps<{
  components: CanvasComponent[];
  modelValue: boolean;
}>();

// 深拷贝的组件数据，防止预览时修改原始数据
const previewComponents = ref<CanvasComponent[]>([]);

const emit = defineEmits<{
  "update:modelValue": [value: boolean];
  submit: [data: Record<string, any>];
}>();

// 使用计算属性处理双向绑定
const previewVisible = computed({
  get: () => props.modelValue,
  set: (value) => emit("update:modelValue", value),
});

// 组件挂载时初始化
onMounted(() => {
  nextTick(() => {
    // 监听事件总线的值变化事件
    console.log("FormBuilder 正在注册事件监听器");
    EventBus.on("component-value-change", handleEventBusValueChange);
    console.log("FormBuilder 事件监听器注册完成");
  });
});

// 组件卸载时清理事件监听器
onUnmounted(() => {
  EventBus.off("component-value-change", handleEventBusValueChange);
});

const formRef = ref<FormInstance>();

const previewData = ref<Record<string, any>>({});

// 互斥状态管理
const mutexState = ref<Map<string, boolean>>(new Map());

// 选项关联状态管理
const relateState = ref<RelateConfig[]>([]);

// 初始化预览组件数据（深拷贝）
const initPreviewComponents = () => {
  // 使用JSON深拷贝防止修改原始数据
  previewComponents.value = _.cloneDeep(props.components).filter(
    (c: any) => !c.parentId
  );
};

// 初始化预览数据
const initPreviewData = () => {
  previewData.value = {};

  // 处理顶层组件（排除有parentId的组件）
  const topLevelComponents = previewComponents.value.filter(
    (component) => !component.parentId
  );
  // 递归处理组件，包括栅格组件的children
  const processComponents = (components: any[]) => {
    components.forEach((component) => {
      if (component.type === "grid" && component.children) {
        // 如果是栅格组件，递归处理其children
        processComponents(component.children);
      } else {
        // 普通组件，初始化默认值
        const key = component.props?.field || component.id;
        if (key) {
          const defaultValue = getDefaultValue(component.type);
          previewData.value[key] = defaultValue;
          console.log(
            `初始化组件 ${component.props?.label} (${key}):`,
            defaultValue,
            "type:",
            component.type
          );
        }
      }
    });
  };
  processComponents(topLevelComponents);

  console.log("完整的预览数据:", previewData.value);
};

// 获取组件默认值
const getDefaultValue = (type: string): any => {
  // 统一按照 input 组件的标准，所有组件默认值都为空字符串
  switch (type) {
    case "checkbox":
      return []; // 多选框保持数组类型
    case "radio":
      return ""; // 单选框改为空字符串
    case "select":
      return ""; // 下拉选择改为空字符串
    case "number":
      return ""; // 数字输入改为空字符串
    case "date":
      return ""; // 日期选择保持空字符串
    default:
      return ""; // 其他所有组件都为空字符串
  }
};

// 计算画布尺寸
const canvasSize = computed(() => {
  let maxX = 0;
  let maxY = 0;

  previewComponents.value.forEach((component) => {
    // 计算组件实际宽度
    let componentWidth: number;
    if (component.props.widthType === "custom" && component.props.customWidth) {
      componentWidth = component.props.customWidth;
    } else if (component.props.widthType === "full") {
      // 铺满模式使用一个合理的默认宽度来计算画布尺寸
      componentWidth = Math.max(component.size.width, 300);
    } else {
      componentWidth = component.size.width;
    }

    const right = component.position.x + componentWidth;
    const bottom = component.position.y + component.size.height;
    maxX = Math.max(maxX, right);
    maxY = Math.max(maxY, bottom);
  });

  return {
    width: Math.max(800, maxX + 50),
    height: Math.max(600, maxY + 50),
  };
});

// 获取组件样式（模拟画布布局）
const getComponentStyle = (component: CanvasComponent) => {
  // 计算组件宽度
  let componentWidth: string;
  if (component.props.widthType === "custom" && component.props.customWidth) {
    componentWidth = component.props.customWidth + "px";
  } else if (component.props.widthType === "full") {
    componentWidth = "100%";
  } else {
    componentWidth = component.size.width + "px";
  }

  return {
    position: "relative" as const,
    // left: component.position.x + "px",
    // top: component.position.y + "px",
    width: componentWidth,
    // height: component.size.height + "px",
    zIndex: 1,
  };
};

// 检查互斥规则
const checkMutexRules = () => {
  console.log("开始检查互斥规则...");
  // 重置所有组件的隐藏状态
  mutexState.value.clear();

  // 递归处理所有组件（包括栅格内的子组件）
  const processAllComponents = (components: CanvasComponent[]) => {
    components.forEach((component) => {
      if (component.type === "grid" && component.children) {
        // 如果是栅格组件，递归处理其children
        processAllComponents(component.children);
      } else {
        // 检查普通组件的互斥规则
        if (
          component.props.mutexConfig?.enabled &&
          component.props.mutexConfig.rules
        ) {
          const key = component.props.field || component.id;
          const currentValue = previewData.value[key];
          console.log(
            `检查组件 ${component.props.label} (${key}) 的值:`,
            currentValue
          );

          const matchingRule = component.props.mutexConfig.rules.find(
            (rule: MutexRule) => rule.value === currentValue
          );

          if (matchingRule) {
            console.log(
              `找到匹配规则，隐藏组件:`,
              matchingRule.hiddenComponents
            );
            // 隐藏指定的组件（直接使用组件ID）
            matchingRule.hiddenComponents.forEach(
              (hiddenComponentId: string) => {
                mutexState.value.set(hiddenComponentId, true);
                console.log(`隐藏组件: ${hiddenComponentId}`);
              }
            );
          }
        }
      }
    });
  };

  // 处理顶层组件
  const topLevelComponents = previewComponents.value.filter(
    (component) => !component.parentId
  );
  processAllComponents(topLevelComponents);

  console.log("互斥状态:", mutexState.value);
};

// 检查选项关联规则
const checkRelateRules = () => {
  console.log("开始检查选项关联规则...");
  // 重置所有组件的隐藏状态
  relateState.value = [];

  // 递归处理所有组件（包括栅格内的子组件）
  const processAllComponents = (components: CanvasComponent[]) => {
    components.forEach((component) => {
      if (component.type === "grid" && component.children) {
        // 如果是栅格组件，递归处理其children
        processAllComponents(component.children);
      } else {
        // 检查普通组件的选项关联规则

        if (
          component.props?.relateConfig?.enabled &&
          component.props?.relateConfig?.rules
        ) {
          relateState.value.push(component.props?.relateConfig);
        }
      }
    });
  };

  processAllComponents(previewComponents.value);

  console.log("选项关联状态:", relateState.value);
};

// 处理组件值变化
const handleEventBusValueChange = (payload: {
  field: string;
  value: any;
  componentId?: string;
}) => {
  console.log(
    "PreviewDialog 事件总线接收到值变化:",
    payload.field,
    payload.value,
    payload.componentId
  );
  if (payload.field) {
    previewData.value[payload.field] = payload.value;
    console.log("更新后的表单数据:", previewData.value);
    // 重新检查互斥规则
    checkMutexRules();
    // 重新检查选项关联规则
    checkRelateRules();
    // 处理关联项options
    setComponentOptions(payload);
  }
};

// 设置组件选项（调试用）
const setComponentOptions = (payload: {
  field: string;
  value: any;
  componentId?: string;
}) => {
  console.log("组件值变化:", {
    componentId: payload.componentId,
    currentComponentId: payload.componentId,
    label: payload.field,
    value: payload.value,
    relateState: relateState.value,
  });

  // 检查 componentId 是否存在
  if (payload.componentId) {
    const relateItems = relateState.value.find(
      (item: any) => item.dependentComponentId === payload.componentId
    );
    // 这里可以添加处理 rules 的逻辑
    if (relateItems) {
      const ruleItem = relateItems.rules.find(
        (item: any) => item.currentOptionValue === payload.value
      );
      if (ruleItem) {
        const options = ruleItem.dependentOptions;
        // props.components
        const handleSetOptions = (components: any) => {
          components.forEach((component: any) => {
            if (component.type === "grid") {
              handleSetOptions(component.children);
            } else {
              if (component.id === relateItems.currentComponentId) {
                component.props.options = options;
              }
            }
          });
        };
        handleSetOptions(previewComponents.value);
      }
    }
  }
};

// 检查组件是否被隐藏
const isComponentHidden = (componentId: string): boolean => {
  return mutexState.value.get(componentId) || false;
};

// 重置表单
const handleReset = () => {
  if (formRef.value) {
    formRef.value.resetFields();
  }
  // 重新初始化数据
  initPreviewData();
  checkMutexRules();
  checkRelateRules();
};

// 关闭对话框
const handleClose = () => {
  // 重置表单数据
  handleReset();
  // 关闭对话框
  nextTick(() => {
    previewVisible.value = false;
  });
};

// 提交表单
const handleSubmit = (formEl: FormInstance | undefined) => {
  if (!formEl) return;

  console.log("提交前的表单数据:", previewData.value);
  console.log("表单字段列表:", Object.keys(previewData.value));

  formEl.validate((valid, fields) => {
    console.log("表单验证结果:", valid);
    if (!valid) {
      console.log("验证失败的字段:", fields);
    }
    if (valid) {
      console.log("提交表单数据:", previewData.value);
      ElMessage.success("表单提交成功！");
    } else {
      ElMessage.error("表单验证失败，请检查必填项");
    }
  });
};

// 监听props变化，重新初始化组件数据
watch(
  () => props.components,
  () => {
    initPreviewComponents();
    initPreviewData();
    checkMutexRules();
    checkRelateRules();
  },
  { immediate: true }
);
</script>

<style lang="scss">
.preview-dialog-modal {
  .el-overlay-dialog {
    overflow: hidden;
  }
  .grid-item {
    background-color: transparent !important;
  }
  .form-component {
    &:hover {
      outline: none !important;
    }
  }
}
.preview-dialog {
  .el-dialog__body {
    padding: 0;
    height: 750px;
    overflow-y: auto;
    overflow-x: hidden;
  }

  .form-preview {
    // padding: 20px;
    // height: 100vh;
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 15px;
      border-bottom: 1px solid #e4e7ed;

      h2 {
        margin: 0;
        color: #303133;
      }

      .actions {
        display: flex;
        gap: 10px;
      }
    }

    .preview-canvas {
      position: relative;
      background: white;
      border-radius: 4px;
      overflow-y: auto;
      min-width: 800px;
      min-height: 600px;
      margin: 0 auto;
    }

    .preview-component {
      border: 1px dashed transparent;
      border-radius: 4px;
      margin-bottom: 10px;
      &:hover {
        border-color: transparent;
      }
    }
  }

  // 全局样式覆盖
  :deep(.form-component) {
    &:hover {
      border: none !important;
      outline: none !important;
    }
  }

  :deep(.grid-item) {
    &:hover {
      background-color: transparent !important;
    }
  }
}
</style>
